package com.rc.evcharger.redis;

import com.rc.evcharger.common.redis.RedisDao;
import com.rc.evcharger.common.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class RedOccupyServiceImpl implements RedOccupyService {
    Logger logger = LoggerFactory.getLogger(RedOccupyServiceImpl.class);

    @Autowired
    private RedisDao redisDao;

    @Override
    public void putOccupyToRedis(String rtua, String gunNum, Long memberId, Long endTime) {
        if (gunNum.length() == 1) {
            gunNum = "0" + gunNum;
        }
        RedOccupy occupy = new RedOccupy(rtua, gunNum, memberId, endTime);
        redisDao.putHashSession(RedOccupy.OCCUPY, occupy.getKey(), occupy.getValue().toString());
        logger.warn("将资源占用信息存入redis中：" + occupy.toString());
    }

    @Override
    public void delOccupyToRedis(String rtua, String gunNum) {
        if (gunNum.length() == 1) {
            gunNum = "0" + gunNum;
        }
        RedOccupy occupy = new RedOccupy(rtua, gunNum);
        redisDao.delHashKeyMap(RedOccupy.OCCUPY, occupy.getKey());
//        logger.warn("删除资源占用信息：" + occupy.toString());
    }

    @Override
    public RedisOccupy getOccupyToRedis(String rtua, String gunNum) {
        if (gunNum.length() == 1) {
            gunNum = "0" + gunNum;
        }
        RedOccupy occupy = new RedOccupy(rtua, gunNum);
        String target = (String) redisDao.getHashSession(RedOccupy.OCCUPY, occupy.getKey());
        if (target == null || target.equals("null")) {
            return null;
        }
        String[] array = StringUtil.stringToArray(target);

        if (array != null) {
            RedisOccupy redisOccupy = new RedisOccupy();
            redisOccupy.setMemberId(Long.valueOf(array[0].trim()));
            redisOccupy.setDate(new Date(Long.valueOf(array[1].trim())));
            redisOccupy.setOrderId(Long.valueOf(array[2].trim()));
            return redisOccupy;
        }
        return null;
    }
}
